import { getRecordList, addTestRecord, queryActiveRecord, queryTestRecord, deleteTestRecord, updateTestRecord, pmCheckPass, pmCheckFail, testCheckPass, testCheckFail,queryTestCount,querySuccessRate } from '../services/testrecord';
import{setTestStatus} from '../services/testreport'
import {sendDingNews,callUser} from '../services/dingding';
import {deepCopy} from '../utils/utils';
import _ from 'lodash';
import { routerRedux } from 'dva/router';


export default {
  namespace: 'testrecord',

  state: {
    list: [],
    pagination: { total: 0, current: 1, pageSize: 10 },
    selectedRows: [],
    testStatusList: [{ text: '等待提测', value: '0' }, { text: '产品体验', value: '1' }, { text: '测试审核', value: '2' },
    { text: '产品打回', value: '3' }, { text: '测试打回', value: '4' }, { text: '已提测', value: '5' }],
    formData: {},
    activeRecord: {},
    formModalVisible: false,
    users: undefined,
    historyRecordList: undefined,
    testcount:0,
    successrate:0
  },

  subscriptions: {
    /**
     * 监听浏览器地址
     * @param dispatch 触发器，用于触发 effects 中的 方法
     * @param history 浏览器历史记录，主要用到它的 location 属性以获取地址栏地址
     */
    setup({ dispatch, history }) {
      history.listen((location) => {
        if (history.action === 'POP' && history.location.pathname === "/testcenter/testsubmit/confirm") {
          dispatch({
            type: 'gotoTestRecordFormPage',
            payload: {}
          })
        }

        if (history.action === 'POP' && history.location.pathname === "/testcenter/testsubmit/result") {
          dispatch({
            type: 'gotoTestRecordPage',
            payload: {}
          })
        }
        if (history.location.pathname === "/testcenter/testrecord") {
          dispatch({
            type: 'saveFormData',
            payload: {}
          })
        }
      });
    },
  },

  effects: {
    *list({ payload }, { call, put, select }) {

      let filtersArg = payload.filtersArg;
      let sorter = payload.sorter;
      let pagination = payload.pagination;

      if (!payload.pagination) {
        pagenation = yield select(state => state.testrecord.pagination);
      }

      if (filtersArg) {
        if (filtersArg.projectName) {
          if (!_.isEmpty(filtersArg.projectName)) {
            filtersArg.projectId = filtersArg.projectName;
          }
          delete filtersArg.projectName
        }
        if (_.isEmpty(filtersArg.testStatus)) {
          delete filtersArg.testStatus
        }
      }

      if (sorter) {
        sorter = { order: sorter.order, field: sorter.field }
      }

      let response = yield call(getRecordList, { page: pagination.current, size: pagination.pageSize, ...filtersArg, sorter });
      if (response.code === 0) {
        let total = response.data.count;
        pagination.total = total;
        let newPageCount = Math.ceil(total / pagination.pageSize);
        if (newPageCount < pagination.current) {
          pagination.current = 1;
        }
        yield put({
          type: 'setTableData',
          payload: { list: response.data.activeRecordList, pagination }
        })
      }
    },
    *add({ payload }, { call, put }) {
      yield put({
        type: 'saveFormData',
        payload: payload,
      });
      let params = { ...payload };
      let projectName = params.project.name
      let projectVersion = params.version.name
      let text = `${projectName} ${projectVersion}已提测`
      let title = "项目提测提示"
      let ding = {
        projectName:projectName,
        text:text,
        title:title
      }
      delete params.version;
      delete params.project;
      delete params.pm;
      delete params.tester;
      delete params.developer;
      params.selfTestStatus = params.selfTestStatus ? 0 : 1;
      let response = yield call(addTestRecord, params);
      if (response.code == 0) {
        yield put(routerRedux.push('/testcenter/testsubmit/result'));
        yield call(sendDingNews,ding);
      }
    },
    *edit({ payload }, { call, put }) {
      let response = yield call(updateTestRecord, payload);
      yield put({
        type: 'setFormModalVisible',
        payload: false
      })
    },
    *delete({ payload }, { call, put, select }) {
      let response = yield call(deleteTestRecord, payload);
      if (response.code === 0) {
        let { pagination, selectedRows, formData } = yield select(state => state.testrecord);
        let listquery = yield call(getRecordList, { page: pagination.current, size: pagination.pageSize, ...filtersArg, sorter });
        if (listquery.code === 0) {
          let total = response.data.count;
          pagination.total = total;
          let newPageCount = Math.ceil(total / pagination.pageSize);
          if (newPageCount < pagination.current) {
            pagination.current = 1;
          }
          yield put({
            type: 'setTableData',
            payload: { list: listquery.data.activeRecordList, pagination }
          })
        }
      }
    },
    *gotoTestRecordFormPage({ payload }, { put }) {
      yield put(routerRedux.push('/testcenter/testsubmit/info', payload));
    },
    *gotoTestRecordPage({ payload }, { put }) {
      yield put(routerRedux.push('/testcenter/testrecord'));
    },
    *showEditForm({ payload }, { call, put }) {
      let response = yield call(queryActiveRecord, payload.versionId);
      if (response.code === 0) {
        yield put({
          type: 'setActiveRecord',
          payload: response.data.lastTestRecord
        })
        yield put({
          type: 'setFormModalVisible',
          payload: true
        })
      }

    },
    *saveFirstStepFormData({ payload }, { put }) {
      yield put({
        type: 'saveFormData',
        payload: payload
      })
    },
    *pmCheckPass({ payload }, { call, put }) {
      let response = yield call(pmCheckPass, payload.id);
      let text = `${payload.name} ${payload.version}产品体验通过`
      let ding = {
        projectName:payload.name,
        text:text,
        title:"产品体验通过"
      }
      if (response.code === 0) {
        yield call(sendDingNews,ding)
        yield put({
          type: 'replaceTestStatusInList',
          payload: { activeTestRecordId: payload.id, testStatus: 2 }
        })
      }
    },
    *pmCheckFail({ payload }, { call, put }) {
      let response = yield call(pmCheckFail, payload);
      let text = `${payload.name} ${payload.version}产品体验不通过:,${payload.reason}`
      let ding = {
        projectName:payload.name,
        text:text,
        title:"产品打回"
      }
      if (response.code === 0) {
        yield call(sendDingNews,ding)
        yield put({
          type: 'replaceTestStatusInList',
          payload: { activeTestRecordId: payload.id, testStatus: 3 }
        })
      }
    },
    *testCheckPass({ payload }, { call, put }) {
      let response = yield call(testCheckPass, payload.id);
      let reponse = yield call(setTestStatus,payload)
      let text = `${payload.name} ${payload.version}测试审核通过`
      let ding = {
        projectName:payload.name,
        text:text,
        title:"测试审核通过"
      }
      if (response.code === 0) {
        yield call(sendDingNews,ding)
        yield put({
          type: 'replaceTestStatusInList',
          payload: { activeTestRecordId: payload.id, testStatus: 5 }
        })
      }
    },
    *testCheckFail({ payload }, { call, put }) {
      let response = yield call(testCheckFail, payload);
      let text = `${payload.name} ${payload.version}测试审核不通过:,${payload.reason}`
      let ding = {
        projectName:payload.name,
        text:text,
        title:"测试打回"
      }
      if (response.code === 0) {
        yield call(sendDingNews,ding)
        yield put({
          type: 'replaceTestStatusInList',
          payload: { activeTestRecordId: payload.id, testStatus: 4 }
        })
      }
    },
    *queryVersionRecord({ payload }, { call, put }) {
      let response = yield call(queryActiveRecord, payload.versionId);
      if (response.code === 0) {
        yield put({
          type: 'setVersionRecord',
          payload: response.data
        })
        yield put({
          type: 'version/setCurrentVersion',
          payload: response.data.version
        })
      }
    },
    *gotoRecordDetailPage({ payload }, { put }) {
      yield put(routerRedux.push('/testcenter/testrecorddetail', payload));
    },
    *callUser({payload},{call}){
      let text = '提测进度跟新，请处理'
      let ding = {
        text:text,
        mobile:payload.mobile,
        projectName:payload.projectName
      }
      let response = yield call(callUser,ding)
    },
    *handleHistoryCollapse({ payload }, { call, put, select }) {
      let hrl = yield select(state => state.testrecord.historyRecordList);
      let historyRecord = deepCopy(hrl);
      if (historyRecord && historyRecord.length > 0) {
        let newRecordId = _.toInteger(_.takeRight(payload.params)[0]);
        let activeRecordId = _.toInteger(historyRecord[0].id);
        let newRecordIndex = _.findIndex(historyRecord, function (hr) {
          return (hr.id === newRecordId) && (hr.id !== activeRecordId);
        });
        if (newRecordIndex > -1) {
          let testRecord = historyRecord[newRecordIndex];
          if (!testRecord.recordLog) {
            let response = yield call(queryTestRecord, testRecord.id);
            if (response.code === 0) {
              testRecord = { ...response.data.testRecord,  recordLog: response.data.recordLog };
              historyRecord[newRecordIndex] = testRecord;
              yield put({
                type: 'setHistoryRecordList',
                payload: historyRecord
              })
            }

          }
        }
      }
    },
    *queryTestNumber({payload},{call,put}){
      let resulet = yield call(queryTestCount,payload)
      if(resulet.code ==0){
        yield put({
          type:'setTestCount',
          payload:resulet.data
        })
      }
    },
    *querySuccessRate({payload},{call,put}){
      let resulet = yield call(querySuccessRate,payload)
      if(resulet.code ==0){
        yield put({
          type:'setLaunchTestSuccessRate',
          payload:resulet.data
        })
      }
    }

  },

  reducers: {
    setTableData(state, action) {
      let listdata = action.payload.list;
      listdata = listdata.map(record => {
        return _.merge(record, { key: record.versionId })
      });

      return {
        ...state,
        list: listdata,
        pagination: action.payload.pagination
      }
    },
    setSelectedRows(state, action) {
      return {
        ...state,
        selectedRows: action.payload
      }
    },
    saveFormData(state, action) {
      return {
        ...state,
        formData: action.payload
      }
    },
    replaceTestStatusInList(state, action) {
      let params = action.payload;
      let list = state.list;
      list.forEach(testrecord => {
        if (testrecord.activeTestRecordId === params.activeTestRecordId) {
          testrecord.testStatus = params.testStatus;
        }
      });
      return {
        ...state,
        list: list
      }
    },
    setFormModalVisible(state, action) {
      return {
        ...state,
        formModalVisible: action.payload
      }
    },
    setActiveRecord(state, action) {
      return {
        ...state,
        activeRecord: action.payload
      }
    },
    setVersionRecord(state, action) {
      let { users, testRecordList } = action.payload;

      return {
        ...state,
        historyRecordList: testRecordList,
        users: users,
      }
    },
    setHistoryRecordList(state, action) {
      return {
        ...state,
        historyRecordList: action.payload
      }
    },
    setTestCount(state,action){
      return{
        ...state,
        testcount:action.payload
      }
    },
    setLaunchTestSuccessRate(state,action){
      return{
        ...state,
        successrate:action.payload
      }
    }
  },

};
